<!-- 设置动态表单组件--中间表单预览 -->
<template>
  <div class="tabs">
    <!-- <a-tabs lazy-load>
      :style="{
        backgroundColor: '#fff',
      }"
      type="rounded"
      position="left"
      :editable="true"
      @delete="handleDelete"
      show-add-button
      auto-switch
      @change="tabClick"
      @tab-click="add"
    >
      <a-tab-pane v-for="item in tabList" :key="item.key">
        <template #title>
          <span v-if="!item.isEdit">{{ item.title }}</span>
          <a-input
            v-model="item.title"
            :style="{
              width: '100px',
            }"
            v-else
          ></a-input>
          <icon-edit
            :style="{
              marginLeft: '10px',
              cursor: 'pointer',
            }"
            @click.stop="editTitle(item.key)"
          />
        </template>
      </a-tab-pane>
    </a-tabs> -->
    <draggable
      :list="store.tabList"
      group="tabs"
      itemKey="tabs"
      class="draggable"
      @change="sorted('tabs')"
      draggable=".item"
    >
      <template #item="{ element }">
        <div :class="element.key !== -1 ? 'item' : ''">
          <a-tabs lazy-load>
            :style="{ backgroundColor: '#fff' }" type="rounded" position="left"
            :editable="true" @delete="handleDelete" @change="tabClick"
            @tab-click="add" :default-active-key="0"
            v-model:active-key="selectedTab" >
            <a-tab-pane :key="element.key">
              <template #title>
                <span v-if="!element.isEdit">{{ element.name }} </span>
                <a-input
                  v-model="element.name"
                  :style="{
                    width: '100px'
                  }"
                  @change="titleChange(element)"
                  v-else
                ></a-input>
                <icon-edit
                  :style="{
                    marginLeft: '10px',
                    cursor: 'pointer'
                  }"
                  @click.stop="editTitle(element.key)"
                />
              </template>
            </a-tab-pane>
          </a-tabs>
        </div>
      </template>
    </draggable>
  </div>
  <div class="center">
    <a-scrollbar style="height: 850px; overflow: auto">
      <div v-for="(item, index) in copySetUpList" :key="index">
        <a-form
          :model="item.componentModel"
          autoLabelWidth
          :layout="(layout as Tlayout)"
          v-if="index === currIndex"
        >
          <draggable
            :list="item.componentModel"
            group="people"
            itemKey="controlName"
            class="draggable"
            @change="sorted('form')"
            @end="onEnd"
          >
            <template #item="{ element, index }">
              <div
                :class="
                  choiceUuid === element.uuid
                    ? 'center-item-choice'
                    : 'center-item'
                "
                :style="{
                  width: element.span === 12 ? '320px' : '660px'
                }"
              >
                <div
                  class="form-item"
                  :class="element.required === 1 ? 'require' : ''"
                  @click="removeAt(element, index)"
                >
                  <div class="fill"></div>
                </div>
                <FormItem
                  :name="element?.name"
                  :code="element?.code"
                  :componentType="element?.componentType"
                  :props="element?.props"
                  :required="element?.required"
                  :values="fakeValue"
                />
                <div class="mask" @click="emit('choiceComponent', element)" />
              </div>
            </template>
          </draggable>
        </a-form>
      </div>
    </a-scrollbar>
    <a-button class="saveForm" @click="saveField" type="outline">保存</a-button>
  </div>
</template>

<script setup lang="ts">
import uniqueid from 'lodash.uniqueid';
import { useSetupFormStore } from '@/store';
import mitter from '@/utils/mitt';
import draggable from 'vuedraggable';
import { PostOrganizaitonTemplate } from '@/apis/management/organization/baseSetting/organizationalType';
import { PostPositionTemplate } from '@/apis/management/organization/baseSetting/PositionSystem';
import { PostHumanTemplate } from '@/apis/management/human/baseSetting/humanSetting';
import FormItem from '../../../rendering-form/form-item/index.vue';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';

const emit = defineEmits(['choiceComponent', 'update:setUpList']);
const fakeValue = ref(['']);

const props = withDefaults(
  //参数说明
  defineProps<{
    setUpList: any; //tab显示的tab列表
    choiceUuid: string;
    layout: string;
  }>(),
  {}
);

const store = useSetupFormStore();

let selectedTab = ref(0); // 储存当前所点击的标签
let currIndex = ref(0); // 获取现在点击标签的index
let currCollectionId = 0; // 储存当前所点击标签页的CollectionId

// const copySetUpList: any = computed(() => {
//   return props.setUpList;
// });
let copySetUpList = ref();

watch(
  () => props.setUpList,
  (newVal) => {
    copySetUpList.value = newVal;
  },
  {
    deep: true
  }
);

const onEnd = (val) => {
  console.log('center');

  console.log(val);
};
// 储存标签
// const tabList: any = ref<any>([
//   {
//     name: '基础信息',
//     key: 0,
//     isEdit: false,
//     sort: 0
//   },
//   // {
//   //   title: '工商信息',
//   //   key: 1,
//   //   isEdit: false,
//   // },
//   {
//     name: '新增',
//     key: -1,
//     isEdit: false
//   }
// ]);

// 点击表单名称标签
const tabClick = (key: number) => {
  if (key !== -1) {
    currIndex.value = key;
    // store.tabList.forEach((item: any) => {
    //   item.isEdit = false;
    // });
    store.tabList.forEach((item: any) => {
      item.isEdit = false;
    });
    mitter.emit('formTabChange', key);
  }
};

// 新增一个标签名字
const add = (key: number) => {
  console.log(key);

  console.log(store.tabList);
  if (key === -1) {
    const item = {
      name: '',
      key: store.tabList[store.tabList.length - 2].key + 1,
      sort: store.tabList[store.tabList.length - 2].sort + 1,
      templateId: store.templateId,
      // templateId: 3,
      required: 1,
      isEdit: false
    };

    store.tabList.splice(store.tabList.length - 1, 0, item);
    const temp = {
      componentModel: []
    };
    copySetUpList.value.push(temp);
    // Array.from(copySetUpList.value).push(temp);
    console.log('====================================sdsd');
    console.log(copySetUpList.value);
    console.log(store.tabList);
    console.log('====================================');

    // console.log('====================================大萨达撒');
    // console.log(store.tabList);
    // console.log(tabs.value);
    // console.log('====================================');
    // store.setTabList(store.tabList);
  }
};

// 点击编辑标签名字
const editTitle = (key: number) => {
  store.tabList.forEach((item: any) => {
    item.isEdit = item.key === key ? true : false;
  });
};

// 改变标题
const titleChange = async (record: any) => {
  try {
    console.log('====================================dd');
    console.log(record);
    console.log('====================================');
    const temp = cloneDeep(record);
    delete temp.key;
    delete temp.isEdit;
    console.log(temp);

    let collectionId = 0;
    // 如果是组织类型
    if (store.templateType === 1) {
      collectionId = await PostOrganizaitonTemplate({
        level: 2, // 第二层level为2
        information: temp
      });
    }
    // 职位类型
    else if (store.templateType === 2) {
      collectionId = await PostPositionTemplate({
        level: 2, // 第二层level为2
        positionInformation: temp
      });
    }

    // 人员模板
    else if (store.templateType === 3) {
      collectionId = await PostHumanTemplate({
        level: 2, // 第二层level为2
        positionInformation: temp
      });
    }

    record.collectionId = collectionId;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除一个标签
const handleDelete = (key: number) => {
  if (key !== -1) {
    copySetUpList.value.splice(key, 1);
    store.tabList = store.tabList.filter((item: any) => item.key !== key);
  }
};

// 拖动排序
const sorted = async (name: string) => {
  try {
    if (name === 'form') {
      copySetUpList.value[currIndex.value].componentModel.forEach(
        (item, index) => {
          item.uuid = `${index}`;
          item.sort = index;
        }
      );
      // await PostControl(copySetUpList.value);
    } else if (name === 'tabs') {
      store.tabList.forEach((item, index) => {
        item.sort = index;
      });
    }
  } catch (error) {
    console.log(error);
  }
};

// 每新增一个表单就保存
const saveField = async () => {
  try {
    // let collectionId;
    // console.log('====================================');
    // console.log(store.tabList[currIndex.value]);
    // console.log('====================================');
    // if (store.tabList[currIndex.value].id)
    //   collectionId = store.tabList[currIndex.value].id;
    // else if (store.tabList[currIndex.value].collectionId)
    //   collectionId = store.tabList[currIndex.value].collectionId;
    // else
    //   collectionId =
    //     store.tabList[currIndex.value]?.componentModel[0]?.collectionId;
    let collectionId =
      store.tabList[currIndex.value].id ||
      store.tabList[currIndex.value].collectionId ||
      store.tabList[currIndex.value]?.componentModel[0]?.collectionId;
    console.log(collectionId);

    const temp = cloneDeep(copySetUpList.value[currIndex.value].componentModel);
    temp.forEach((item: any, index: number) => {
      item.orderNo = item.sort || index;
      item.controlId = item.id;
      item.props = JSON.stringify(item.props);
      if (collectionId) item.collectionId = collectionId;
      else item.collectionId = store.tabList[currIndex.value].collectionId;
      // delete item.id;
      // delete item.fieldName;

      /* 判断是新增还是编辑，如果是新增则不用传id */
      if (!item.controlModel) delete item.id;
      delete item.sort;
      // delete item.uuid;
    });

    // 如果是组织类型
    if (store.templateType === 1) {
      await PostOrganizaitonTemplate({
        level: 3, // 第三层
        field: temp
      });
    }
    // 职位类型
    else if (store.templateType === 2) {
      await PostPositionTemplate({
        level: 3, // 第三层
        field: temp
      });
    }

    // 人员模板
    else if (store.templateType === 3) {
      await PostHumanTemplate({
        level: 3, // 第三层
        field: temp
      });
    }
    console.log(temp);
  } catch (error: unknown) {
    console.log(error);
  }
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
const removeAt = (element: any, index: number) => {
  if (element.isMust === 1) Message.error('默认的控件不能手动删除！');
  else copySetUpList.value[currIndex.value].componentModel.splice(index, 1);
};

onMounted(() => {
  // store.setTabList(store.tabList);
});

// defineExpose({ tabList });
</script>

<style lang="less" scoped>
.tabs {
  // position: absolute;
  // left: -107px;
}
.center {
  background: rgb(255, 255, 255);
  width: 700px;
  padding: 20px;
  height: 90vh;
  border-radius: 10px;
  // overflow-x: hidden;

  .draggable {
    height: 600px;
    display: flex;
    justify-content: space-between;
    align-content: flex-start;
    flex-wrap: wrap;
  }

  &-item {
    position: relative;
    border: #fff solid 1px;

    .form-item {
      display: flex;
      height: 20px;

      .fill {
        flex: 1;
      }
    }
    .form-item::before {
      content: '';
      width: 0;
      height: 0;
      border-top: 15px solid skyblue;
      border-right: 15px solid transparent;
    }
    .require::before {
      content: '';
      width: 0;
      height: 0;
      border-top: 15px solid rgb(136, 138, 139) !important;
      border-right: 15px solid transparent;
    }
  }

  .mask {
    position: absolute;
    left: 0;
    bottom: 0;
    right: 0;
    top: 0;
    cursor: pointer;
  }

  &-item-choice {
    position: relative;

    // border: rgb(73, 56, 148) solid 1px;
    .mask {
      // background: rgba(22, 93, 255, 0.2);
      border: #3296fa solid 1px;
    }
  }

  &-item-choice {
    .form-item {
      // pointer-events: none;
      display: flex;
      height: 20px;

      .fill {
        flex: 1;
      }
    }

    .form-item::after {
      z-index: 999;
      content: '\2716';
      width: 20px;
      height: 20px;
      text-align: center;
      color: #3296fa;
    }
    .require::after {
      z-index: 999;
      content: '';
      width: 20px;
      height: 20px;
      text-align: center;
      color: #3296fa;
    }
    .form-item::before {
      content: '';
      width: 0;
      height: 0;
      border-top: 15px solid skyblue;
      border-right: 15px solid transparent;
    }
    .require::before {
      content: '';
      width: 0;
      height: 0;
      border-top: 15px solid rgb(136, 138, 139) !important;
      border-right: 15px solid transparent;
    }
  }

  &-item:hover {
    border: #3296fa dashed 1px;

    .form-item {
      // pointer-events: none;
      display: flex;

      .fill {
        flex: 1;
      }
    }

    .form-item::after {
      z-index: 999;
      content: '\2716';
      width: 20px;
      height: 20px;
      text-align: center;
      color: #3296fa;
    }
    .require::after {
      z-index: 999;
      content: '';
      width: 20px;
      height: 20px;
      text-align: center;
      color: #3296fa;
    }
  }
  .saveForm {
    float: right;
    top: 30px;
  }
}
</style>
